<script setup lang="tsx">
import { computed, reactive, ref, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import type { DictType } from '@/service/api';
import { createDictType, updateDictType } from '@/service/api';
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict';

defineOptions({
  name: 'DictTypeOperateModal'
});

export type OperateType = NaiveUI.TableOperateType;

interface Props {
  /** the type of operation */
  operateType: OperateType;
  /** the edit menu data or the parent menu data when adding a child menu */
  rowData?: DictType | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const submitLoading = ref(false);

const title = computed(() => {
  const titles: Record<OperateType, string> = {
    add: $t('page.manage.dict.type.addDictType'),
    edit: $t('page.manage.dict.type.editDictType')
  };
  return titles[props.operateType];
});

type Model = Pick<DictType, 'name' | 'type' | 'status' | 'remark'> & {
  id: number | null;
};

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    id: null,
    name: '',
    type: '',
    status: 1,
    remark: ''
  };
}

type RuleKey = Extract<keyof Model, 'name' | 'status' | 'type'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  name: defaultRequiredRule,
  status: defaultRequiredRule,
  type: defaultRequiredRule
};

function closeDrawer() {
  submitLoading.value = false;
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  submitLoading.value = true;

  if (props.operateType === 'edit') {
    // request
    const { error } = await updateDictType(model.id as number, model);

    if (!error) {
      window.$message?.success($t('common.updateSuccess'));
      closeDrawer();
      emit('submitted');
    }
  } else {
    const { error } = await createDictType(model);
    if (!error) {
      window.$message?.success($t('common.addSuccess'));
      closeDrawer();
      emit('submitted');
    }
  }
}

async function handleInitModel() {
  Object.assign(model, createDefaultModel());

  if (!props.rowData) return;

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});
</script>

<template>
  <NModal v-model:show="visible" :title="title" preset="card" :mask-closable="false" class="w-200">
    <NScrollbar class="max-h-200 pr-20px">
      <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" label-width="auto">
        <NFormItem :label="$t('page.manage.dict.type.name')" path="name">
          <NInput v-model:value="model.name" :placeholder="$t('page.manage.dict.type.form.name')" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.dict.type.type')" path="type">
          <NInput v-model:value="model.type" :placeholder="$t('page.manage.dict.type.form.type')" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.dict.type.status')" path="status">
          <NRadioGroup v-model:value="model.status">
            <NRadio
              v-for="item in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </NRadioGroup>
        </NFormItem>
        <NFormItem :label="$t('page.manage.dict.type.remark')" path="remark">
          <NInput v-model:value="model.remark" :placeholder="$t('page.manage.dict.type.form.remark')" type="textarea" />
        </NFormItem>
      </NForm>
    </NScrollbar>
    <template #footer>
      <NSpace justify="end" :size="16">
        <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
        <NButton type="primary" :loading="submitLoading" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped>
.flex-end {
  display: flex;
  justify-content: flex-end;
}
</style>
